package com.ruoyi.system.socket;

import com.ruoyi.common.utils.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(2317);
            System.out.println("Waiting for clients on port: " + 2317);

            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected: " + clientSocket.getRemoteSocketAddress());

            DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream());

            InputStream ips = clientSocket.getInputStream();
            OutputStream ops = clientSocket.getOutputStream();


            String hexString = "01 03 00 25 00 02 D5 C0";
            byte[] bytes = hexStrToBinaryStr(hexString);
            dos.write(hexString.getBytes());  // 输出一句话给客户端
            dos.flush();
            dos.close();
            dos = new DataOutputStream(clientSocket.getOutputStream());
            dos.write(hexString.getBytes());
            dos.flush();

            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] dataBuffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = ips.read(dataBuffer)) != -1) {
                buffer.write(dataBuffer, 0, bytesRead);
            }
            byte[] data = buffer.toByteArray();
            System.out.println("res:");
            if (data.length>0) {
                System.out.print(BinaryToHexString(data));
                String res = BinaryToHexString(data);

            }

            dos.close();
            ips.close();
            ops.close();
            clientSocket.close();
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] hexStrToBinaryStr(String hexString) {
        if (StringUtils.isEmpty(hexString)) {
            return null;
        }
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        int index = 0;
        byte[] bytes = new byte[len / 2];
        while (index < len) {
            String sub = hexString.substring(index, index + 2);
            bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
            index += 2;
        }
        return bytes;
    }

    public static String BinaryToHexString(byte[] bytes) {
        String hexStr = "0123456789ABCDEF";
        String result = "";
        String hex = "";
        for (byte b : bytes) {
            hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
            hex += String.valueOf(hexStr.charAt(b & 0x0F));
            result += hex + " ";
        }
        return result;
    }
}